package cn.wen.base.adapter.viewpager;

import android.content.Context;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

/**
 * ViewPager的Holder类
 */

public abstract class QuickPagerHolder<T> implements PagerHolder<T> {
    private View mView;
    private SparseArray<View> mViews = new SparseArray<>();

    @Override
    public View onCreateView(Context context) {
        mView = LayoutInflater.from(context).inflate(getLayoutId(), null, false);
        return mView;
    }

    @Override
    public void onBind(Context context, int position, T t) {
        onBind(this, context, position, t);
    }

    protected abstract void onBind(QuickPagerHolder<T> holder, Context context, int position, T t);

    public abstract int getLayoutId();

    public QuickPagerHolder setText(int id, CharSequence text) {
        TextView tv = getView(id);
        if (tv != null && !TextUtils.isEmpty(text)) {
            tv.setText(text);
        }
        return this;
    }

    public QuickPagerHolder setOnClickListener(int id, View.OnClickListener listener) {
        View view = getView(id);
        if (view != null && listener != null) {
            view.setOnClickListener(listener);
        }
        return this;
    }

    public <V extends View> V getView(int id) {
        View view = mViews.get(id);
        if (view == null) {
            view = mView.findViewById(id);
            if (view != null) {
                mViews.put(id, view);
            }
        }
        return (V) view;
    }

    public View getView() {
        return mView;
    }

    public void setOnClickListener(View.OnClickListener onClickListener) {
        mView.setOnClickListener(onClickListener);
    }
}
